<template>
  <div>
    <!-- 导航栏 -->
    <div class="navbar">
      <div class="logo">
        <img src="@/assets/logo.jpg" class="logo">
        <span>AI小医聊</span>
      </div>
      <div class="buttons"> 
        <button id="logout-btn" @click="$router.push('/Index')">返回首页</button>
      </div>
    </div>

    <!-- 主体布局 -->
    <div class="main-container">
      <!-- 左侧历史记录 -->
      <div class="history-panel">
        <button class="new-chat-button" @click="startNewConversation">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="12" y1="5" x2="12" y2="19"></line>
            <line x1="5" y1="12" x2="19" y2="12"></line>
          </svg>
          新建对话
        </button>

        <h3>历史记录</h3>

        <div class="history-items">
          <div 
            v-for="conv in sortedConversations" 
            :key="conv.id"
            class="history-item"
            :class="{ active: conv.id === currentConversationId }"
            @click="loadConversation(conv.id)"
          >
            <div :style="{ fontWeight: conv.id === currentConversationId ? 'bold' : 'normal' }">{{ conv.title }}</div>
            <div style="font-size: 12px; color: #6b7280; margin-top: 4px;">
              {{ new Date(conv.timestamp).toLocaleString() }}
            </div>
          </div>
        </div>

        <button class="clear-history-button" @click="clearHistory">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="3 6 5 6 21 6"></polyline>
            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
            <line x1="10" y1="11" x2="10" y2="17"></line>
            <line x1="14" y1="11" x2="14" y2="17"></line>
          </svg>
          清除历史
        </button>
      </div>

      <!-- 中间聊天区域 -->
      <div class="chat-panel">
        <div class="chat-messages" ref="chatMessages">
          <div 
            v-for="(message, index) in displayedMessages" 
            :key="index"
            class="message"
            :class="message.role"
          >
            <div class="message-avatar">
              {{ message.role === 'user' ? '你' : 'AI' }}
            </div>
            <div class="message-content" v-html="formatMessageText(message.content)"></div>  
          </div>
          <div v-if="isWaitingForResponse" class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
        <div class="chat-input-container">
          <div class="chat-input">
            <textarea 
              v-model="userInput" 
              @keydown.enter.exact.prevent="sendMessage"
              @input="adjustTextareaHeight"
              placeholder="输入消息..." 
              rows="1"
              :disabled="isWaitingForResponse"
            ></textarea>
            <button @click="sendMessage" :disabled="isWaitingForResponse || !userInput.trim()">
              <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="22" y1="2" x2="11" y2="13"></line>
                <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
              </svg>
              发送
            </button>
          </div>
        </div>
      </div>

      <!-- 右侧 AI 百科 -->
      <div class="ai-encyclopedia">
        <h3>对话模式</h3>
        <div 
          v-for="role in roleOptions" 
          :key="role.value"
          class="role-option"
          :class="{ active: currentRole === role.value }"
          @click="selectRole(role.value)"
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 8px;">
            <path :d="role.icon"></path>
          </svg>
          {{ role.label }}
        </div>

        <h3>专业领域</h3>
        <div 
          v-for="specialty in specialtyOptions" 
          :key="specialty.value"
          class="role-option"
          :class="{ active: currentRole === specialty.value }"
          @click="selectRole(specialty.value)"
        >
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 8px;">
            <path :d="specialty.icon"></path>
          </svg>
          {{ specialty.label }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios';
// 配置DeepSeek API
const DEEPSEEK_API = {
  BASE_URL: 'https://api.deepseek.com/v1',
  API_KEY:'sk-398084d5d41f4cfc85cfd00b8d02dbad',
  CHAT_COMPLETIONS: '/chat/completions',
  MODEL: 'deepseek-chat' 
};
const apiClient = axios.create({
  baseURL: DEEPSEEK_API.BASE_URL,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${DEEPSEEK_API.API_KEY}` 
  }
});
export default {
    name: 'ChatApp',
    data() {
      return {
        // 状态数据
        currentConversationId: this.generateId(),
        currentRole: 'default',
        conversations: {},
        conversationHistory: [],
        isWaitingForResponse: false,
        userInput: '',
        
        // 角色选项
        roleOptions: [
          { value: 'default', label: '智能助手', icon: 'M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z' },
          { value: 'qa', label: '问答专家', icon: 'M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10zm0-2a8 8 0 1 1 0-16 8 8 0 0 1 0 16zm-1-5h2v2h-2v-2zm0-8h2v6h-2V7z' },
          { value: 'creative', label: '创意写作', icon: 'M12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2z' }
        ],
        
        specialtyOptions: [
          { value: 'medical', label: '医疗咨询', icon: 'M18 8h1a4 4 0 0 1 0 8h-1M2 8h16v9a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4V8zM6 1v3M10 1v3M14 1v3' },
          { value: 'tech', label: '技术支持', icon: 'M2 3h20v14H2zm0 0v18h20V3zm2 2h16v10H4zm2 2h12v6H6zm2 2h8v2H8z' },
          { value: 'legal', label: '法律咨询', icon: 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M16 13H8M16 17H8M10 9H8' }
        ]
      }
    },
    computed: {
      sortedConversations() {
        return Object.values(this.conversations).sort((a, b) => b.timestamp - a.timestamp)
      },
      displayedMessages() {
        return this.conversationHistory.filter(msg => msg.role !== 'system')
      }
    },
    mounted() {
      this.loadConversations()
      this.startNewConversation()
    },
    methods: {
      generateId() {
        return Date.now().toString() + Math.random().toString(36).substr(2, 9)
      },
      adjustTextareaHeight() {
        const textarea = this.$el.querySelector('textarea')
        textarea.style.height = 'auto'
        textarea.style.height = Math.min(textarea.scrollHeight, 150) + 'px'
      },
      formatMessageText(text) {
        let formatted = text.replace(/\n/g, '<br>')
        formatted = formatted.replace(/```([\s\S]*?)```/g, '<pre>$1</pre>')
        formatted = formatted.replace(/`([^`]+)`/g, '<code>$1</code>')
        return formatted
      },
      getSystemMessageForRole(role) {
        const roleMessages = {
          'default': '你是一个乐于助人的AI助手，用友好、专业的语气回答问题。',
          'qa': '你是一个知识渊博的问答专家，用准确、简洁的方式回答问题。',
          'creative': '你是一个富有创造力的写作助手，帮助用户进行创意写作和头脑风暴。',
          'medical': '你是一个专业的医疗顾问，提供准确但不替代专业医生的医疗建议。',
          'tech': '你是一个技术专家，帮助解决编程、硬件和软件相关问题。',
          'legal': '你是一个法律顾问，提供一般性法律信息但不构成正式法律建议。'
        }
        return roleMessages[role] || roleMessages['default']
      },
      getTemperatureForRole(role) {
        const roleTemperatures = {
          'default': 0.7,
          'qa': 0.3,
          'creative': 0.9,
          'medical': 0.5,
          'tech': 0.6,
          'legal': 0.4
        }
        return roleTemperatures[role] || 0.7
      },
      getRoleName(role) {
        const roleNames = {
          'default': '智能助手',
          'qa': '问答专家',
          'creative': '创意写作',
          'medical': '医疗咨询',
          'tech': '技术支持',
          'legal': '法律咨询'
        }
        return roleNames[role] || '智能助手'
      },
      async sendMessage() {
      const message = this.userInput.trim();
      if (!message || this.isWaitingForResponse) return;

      // 添加用户消息（修改为仅保留最近5条历史）
      this.conversationHistory.push({ 
        role: 'user', 
        content: message,
        timestamp: Date.now()
      });

      // 保存滚动位置
      const scrollContainer = this.$refs.chatMessages;
      const shouldScroll = scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight - 50;

      // 清空输入框并禁用
      this.userInput = '';
      this.isWaitingForResponse = true;

      try {
        // 获取AI回复
        const aiResponse = await this.getAIResponse();
        
        // 添加AI回复
        this.conversationHistory.push({ 
          role: 'assistant', 
          content: aiResponse,
          timestamp: Date.now()
        });

        // 自动滚动逻辑
        this.$nextTick(() => {
          if (shouldScroll) {
            scrollContainer.scrollTop = scrollContainer.scrollHeight;
          }
        });
      } catch (error) {
        this.conversationHistory.push({
          role: 'assistant',
          content: `错误：${error.message}`
        });
      } finally {
        this.isWaitingForResponse = false;
        this.saveConversation();
      }
    },
      async getAIResponse() {
      try {
        // 构造请求数据
        const messages = this.conversationHistory
          .filter(m => m.role !== 'system')
          .map(m => ({
            role: m.role === 'user' ? 'user' : 'assistant',
            content: m.content
          }));

        // 添加系统消息
        messages.unshift({
          role: 'system',
          content: this.getSystemMessageForRole(this.currentRole)
        });

        const response = await apiClient.post(DEEPSEEK_API.CHAT_COMPLETIONS, {
          model: DEEPSEEK_API.MODEL,
          messages: messages,
          temperature: this.getTemperatureForRole(this.currentRole),
          max_tokens: 2000,
          stream: false // 如需流式响应需要修改为true并调整处理逻辑
        });

        // 处理响应
        if (response.data?.choices?.[0]?.message?.content) {
          return response.data.choices[0].message.content;
        }
        throw new Error('Invalid API response structure');
      } catch (error) {
        console.error('API Error:', error.response?.data || error.message);
        throw new Error('获取响应失败，请检查API配置或网络连接');
      }
    },
      selectRole(role) {
        // 更新当前角色
        this.currentRole = role
        
        // 如果是新对话，直接更新系统消息
        if (this.conversationHistory.length <= 1) {
          this.conversationHistory[0] = { 
            role: 'system', 
            content: this.getSystemMessageForRole(role) 
          }
        } else {
          // 否则提示用户需要新建对话
          if (confirm(`切换角色到"${this.getRoleName(role)}"将开始新的对话。是否继续？`)) {
            this.startNewConversation()
          }
        }
      },
      startNewConversation() {
        // 保存当前对话
        if (this.conversationHistory.length > 0) {
          this.saveConversation()
        }
        
        // 创建新对话
        this.currentConversationId = this.generateId()
        this.conversationHistory = [
          { 
            role: 'system', 
            content: this.getSystemMessageForRole(this.currentRole) 
          }
        ]
        
        // 添加欢迎消息
        this.conversationHistory.push({
          role: 'assistant',
          content: `你好！我是${this.getRoleName(this.currentRole)}，有什么可以帮你的吗？`
        })
        
        // 更新历史记录面板
        this.updateHistoryPanel()
      },
      updateConversationTitle(firstMessage) {
        const title = firstMessage.length > 30 
          ? firstMessage.substring(0, 30) + '...' 
          : firstMessage
        
        if (this.conversations[this.currentConversationId]) {
          this.conversations[this.currentConversationId].title = title
        }
      },
      getConversationTitle() {
        // 尝试从对话历史中找第一条用户消息
        const userMessage = this.conversationHistory.find(m => m.role === 'user')
        if (userMessage) {
          return userMessage.content.length > 30 
            ? userMessage.content.substring(0, 30) + '...' 
            : userMessage.content
        }
        
        // 如果没有用户消息，使用默认标题
        return `与${this.getRoleName(this.currentRole)}的对话`
      },
      saveConversation() {
        this.conversations[this.currentConversationId] = {
          id: this.currentConversationId,
          title: this.getConversationTitle(),
          role: this.currentRole,
          history: [...this.conversationHistory],
          timestamp: Date.now()
        }
        
        this.saveConversationsToStorage()
        this.updateHistoryPanel()
      },
      saveConversationsToStorage() {
        try {
          localStorage.setItem('deepseek-chat-conversations', JSON.stringify(this.conversations))
        } catch (e) {
          console.error('保存对话失败:', e)
        }
      },
      loadConversations() {
        try {
          const saved = localStorage.getItem('deepseek-chat-conversations')
          if (saved) {
            this.conversations = JSON.parse(saved)
          }
        } catch (e) {
          console.error('加载对话失败:', e)
        }
      },
      updateHistoryPanel() {
        // 计算属性 sortedConversations 会自动更新
      },
      loadConversation(conversationId) {
        const conversation = this.conversations[conversationId]
        if (!conversation) return
        
        // 设置当前对话
        this.currentConversationId = conversationId
        this.currentRole = conversation.role || this.DEFAULT_ROLE
        this.conversationHistory = [...conversation.history]
        
        // 滚动到底部
        this.$nextTick(() => {
          this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight
        })
      },
      clearHistory() {
        if (confirm('确定要清除所有历史记录吗？此操作不可撤销。')) {
          this.conversations = {}
          localStorage.removeItem('deepseek-chat-conversations')
          this.startNewConversation()
        }
      }
    }
  }
</script>
<style scoped>
@import '../assets/css/AI_helper.css';
</style>